import {Message} from 'element-ui'
import cookie from 'js-cookie'

export default function ({$axios, redirect}) {
    $axios.onRequest((config) => {
        let userInfo = cookie.get('userInfo')
        if (userInfo) {
            // debugger
            userInfo = JSON.parse(userInfo)
            config.headers['token'] = userInfo.token
        }
        console.log('Making request to ' + config.url)
    })

    $axios.onRequestError((error) => {
        console.log('onRequestError', error) // for debug
    })

    $axios.onResponse((response) => {
        console.log('Reciving resposne', response)
        if (response.data.code === 0) {
            return response
        } else if (response.data.code === -211) {
            console.log('用户校验失败')
            // debugger
            // cookie.set('userInfo', '')
            // 登录状态失效，删除登录的缓存
            localStorage.removeItem('SRB-TOKEN')
            localStorage.removeItem('userInfo')
            //如果后端返回的 responseVo对象的 code值为-211 代表登录状态失效
            setTimeout(() => {
                window.location.href = '/'
            }, 1500)
            return Promise.reject(response) //不放行请求
        } else {
            Message({
                message: response.data.message,
                type: 'error',
                duration: 5 * 1000,
            })
            return Promise.reject(response)
        }
    })

    //通信失败
    $axios.onResponseError((error) => {
        console.log('onResponseError', error) // for debug
    })
}
